//
//  ImageChooseFormObject.m
//  Logistics
//
//  Created by 刘峰 on 2018/1/10.
//  Copyright © 2018年 com.Logistics. All rights reserved.
//

#import "ImageChooseFormObject.h"
#import "PhotoBrowserViewController.h"
#import "NewCameraViewController.h"
#import <Photos/Photos.h>

@interface ImageChooseFormObject ()

{
    CGFloat bottomH;
}
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *cameraBtn;
@property (nonatomic, strong) UIButton *photoBtn;
@property (nonatomic, strong) UIButton *cancleBtn;
@property (nonatomic, weak) UIViewController *currentVc;
@end

@implementation ImageChooseFormObject

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self buildUI];
    }
    return self;
}

- (void)buildUI {
    _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window bringSubviewToFront:_backgroundView];
    [window addSubview:_backgroundView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [_backgroundView addGestureRecognizer:tap];
    
    bottomH = IS_IPHONEX ? 34 : 0;

    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, KscreenHeight-220-bottomH, KscreenWidth, 225+bottomH)];
    _bottomView.backgroundColor = [UIColor whiteColor];
    _bottomView.alpha = 0.7;
    _bottomView.layer.cornerRadius  = 5;
    _bottomView.layer.masksToBounds = YES;
    [window addSubview:_bottomView];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, KscreenWidth-20, 20)];
    _titleLabel.text = @"选择方式";
    _titleLabel.textColor = HEXCOLOR(0x444444);
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [_bottomView addSubview:_titleLabel];
    
    _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancleBtn.frame = CGRectMake(KscreenWidth/2-90, _bottomView.height, 180, 35);
    _cancleBtn.layer.cornerRadius  = 17.5;
    _cancleBtn.layer.masksToBounds = YES;
    _cancleBtn.layer.borderWidth   = 1;
    _cancleBtn.layer.borderColor   = [HEXCOLOR(0x999999) CGColor];
    _cancleBtn.titleLabel.font     = [UIFont systemFontOfSize:15];
    [_cancleBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [_cancleBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
    [_cancleBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_cancleBtn];
    
    _cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cameraBtn.frame = CGRectMake(KscreenWidth/2-40-40, 80, 30, 30);
    [_cameraBtn setImage:[UIImage imageNamed:@"photoBrowser_3"] forState:UIControlStateNormal];
    [_cameraBtn addTarget:self action:@selector(openCameraAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_cameraBtn];
    
    UILabel *camera = [[UILabel alloc] init];
    camera.textAlignment = NSTextAlignmentCenter;
    camera.textColor = HEXCOLOR(0x999999);
    camera.text = @"相机";
    camera.font = [UIFont systemFontOfSize:13];
    [_bottomView addSubview:camera];

    [camera mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_cameraBtn.mas_bottom).offset(5);
        make.centerX.mas_equalTo(_cameraBtn.mas_centerX);
        make.width.mas_equalTo(_cameraBtn.mas_width);
        make.height.mas_equalTo(15);
    }];
    
    _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _photoBtn.frame = CGRectMake(KscreenWidth/2+40+10, 80, 30, 30);
    [_photoBtn setImage:[UIImage imageNamed:@"photoBrowser_4"] forState:UIControlStateNormal];
    [_photoBtn addTarget:self action:@selector(openPhotoAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_photoBtn];

    UILabel *photo = [[UILabel alloc] init];
    photo.textAlignment = NSTextAlignmentCenter;
    photo.textColor = HEXCOLOR(0x999999);
    photo.text = @"相册";
    photo.font = [UIFont systemFontOfSize:13];
    [_bottomView addSubview:photo];
    
    [photo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_photoBtn.mas_bottom).offset(5);
        make.centerX.mas_equalTo(_photoBtn.mas_centerX);
        make.width.mas_equalTo(_photoBtn.mas_width);
        make.height.mas_equalTo(15);
    }];
    _bottomView.hidden     = YES;
    _backgroundView.hidden = YES;
}

- (void)openCameraAction:(UIButton *)sender {
       [self hide];
    [self checkCameraAuthorizationGrand:^{
        NewCameraViewController *camera = [[NewCameraViewController alloc] init];
        [self.currentVc presentViewController:camera animated:YES completion:nil];
    } withNoPermission:nil];
}

- (void)openPhotoAction:(UIButton *)sender {
    [self hide];
    [self checkPhotoAlbumAuthorizationGrand:^{
        PhotoBrowserViewController *photoVc = [[PhotoBrowserViewController alloc] initWithStyle:UITableViewStylePlain];
        [self.currentVc presentViewController:photoVc navigationbarColor:[HEXCOLOR(0x272e33) colorWithAlphaComponent:0.5]];
    } withNoPermission:nil];
}

/**
 检测相机的方法
 @param permissionGranted 相机授权成功执行的方法
 @param noPermission 相机授权失败或者未授权执行的方法
 */
- (void)checkCameraAuthorizationGrand:(void (^)())permissionGranted withNoPermission:(void (^)())noPermission{
    AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (videoAuthStatus) {
        case AVAuthorizationStatusNotDetermined:
        {
            //第一次提示用户授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                granted ? permissionGranted() : noPermission();
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized:
        {
            //通过授权
            permissionGranted();
            break;
        }
        case AVAuthorizationStatusRestricted:
            //不能授权
            NSLog(@"不能完成授权，可能开启了访问限制");
        case AVAuthorizationStatusDenied:{
            //提示跳转相册授权设置
            [[LFAlertBox backgroundAlert] showAlertTitle:@"提示" content:@"请前往系统【设置】->【隐私】->【相机】->【龟米】，开启相机访问权限" cancleText:@"取消" sureText:@"设置" completion:^(NSInteger index) {
                if (index == 1) {
                    [self requetSettingForAuth];
                }
            }];
        }
            break;
        default:
            break;
    }
}

/**
 检测访问相册的权限
 这里的方法适用于iOS8及其以后版本
 @param permissionGranted 相册授权成功执行的方法
 @param noPermission 相册授权失败或者未授权执行的方法
 */
-(void)checkPhotoAlbumAuthorizationGrand:(void (^)())permissionGranted withNoPermission:(void (^)())noPermission{
    PHAuthorizationStatus photoAuthStatus = [PHPhotoLibrary authorizationStatus];
    switch (photoAuthStatus) {
        case PHAuthorizationStatusNotDetermined:
        {
            //第一次提示用户授权
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                status == PHAuthorizationStatusAuthorized ? permissionGranted() : noPermission();
            }];
            break;
        }
        case PHAuthorizationStatusAuthorized:
        {
            //已经通过授权
            permissionGranted();
            break;
        }
        case PHAuthorizationStatusRestricted:
            //不能授权
            NSLog(@"不能完成授权，可能开启了访问限制");
        case PHAuthorizationStatusDenied:{
            //提示跳转相册授权设置
            [[LFAlertBox backgroundAlert] showAlertTitle:@"提示" content:@"请前往系统【设置】->【隐私】->【相机】->【龟米】，开启相机访问权限" cancleText:@"取消" sureText:@"设置" completion:^(NSInteger index) {
                if (index == 1) {
                    [self requetSettingForAuth];
                }
            }];
            break;
        }
        default:
            break;
    }
}

- (void)requetSettingForAuth{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([ [UIApplication sharedApplication] canOpenURL:url])
    {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)showForm:(ImageChooseForm)form InViewController:(UIViewController *)currentVc {
    _currentVc = currentVc;
    switch (form) {
        case ImageChooseFormCustom:{
            [self show];
        }
            break;
        case ImageChooseFormAlertCenter:{
//            [UIAlertController showAlertInViewController:currentVc withTitle:@"请您选择方式" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"从相册中选择" otherButtonTitles:@[@"拍照"] tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
//                if (buttonIndex == controller.firstOtherButtonIndex) {
//                    [self openCameraAction:nil];
//                } else if (buttonIndex == controller.destructiveButtonIndex) {
//                    [self openPhotoAction:nil];
//                }
//            }];
        }
            break;
        default:{
//            [UIAlertController showActionSheetInViewController:currentVc withTitle:@"请您选择方式" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"从相册中选择" otherButtonTitles:@[@"拍照"] popoverPresentationControllerBlock:^(UIPopoverPresentationController * _Nonnull popover) {
//
//            } tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
//                if (buttonIndex == controller.firstOtherButtonIndex) {
//                    [self openCameraAction:nil];
//                } else if (buttonIndex == controller.destructiveButtonIndex) {
//                    [self openPhotoAction:nil];
//                }
//            }];
        }
            break;
    }
    
}

- (void)show {
    _bottomView.hidden     = NO;
    _backgroundView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        _cameraBtn.frame = CGRectMake(KscreenWidth/2-40-50,70, 50, 50);
        _photoBtn.frame = CGRectMake(KscreenWidth/2+40, 70, 50, 50);
        _cancleBtn.y = _bottomView.height - bottomH - 20-35;
    }];
}

- (void)hide {
    _bottomView.hidden     = YES;
    _backgroundView.hidden = YES;

    _backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    _cameraBtn.frame = CGRectMake(KscreenWidth/2-40-40, 80, 30, 30);
    _photoBtn.frame = CGRectMake(KscreenWidth/2+40+10, 80, 30, 30);
    _cancleBtn.y = _bottomView.height;
}



@end
